<?php

namespace app\common\service;

use app\common\exception\Client;
use app\common\exception\Server;
use app\common\model\ThirdApp;
use app\common\domain\Token as tokenDomain;

class AppToken
{
    public function get($ac, $se): string
    {
        $app = ThirdApp::check($ac, $se);
        if(!$app)throw new Client(100004,'授权失败');
        $scope = $app->scope;
        $uid = $app->id;
        $values = [
            'scope' => $scope,
            'uid' => $uid
        ];
        return $this->saveToCache($values);
    }

    private function saveToCache($values): string
    {
        $token = tokenDomain::generateToken();
        $expire_in = config('setting.token_expire_in');
        $result = cache($token, json_encode($values), $expire_in);
        if(!$result){
            throw new Server('服务器缓存异常');
        }
        return $token;
    }
}